package com.aipodcast.webbackend.config;

import com.aipodcast.webbackend.config.model.ApiResponse;
import com.aipodcast.webbackend.config.model.ApiResponseCode;
import com.aipodcast.webbackend.utils.ExceptionUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.nio.file.AccessDeniedException;


/**
 * @author RedStar
 * @date 2025/9/23 22:58
 * @description 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<String>> handleIllegalArgumentException(IllegalArgumentException e) {
        // 参数错误处理
        return ResponseEntity.ok(new ApiResponse<>(ApiResponseCode.BAD_REQUEST, e.getMessage(), null));
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<ApiResponse<Void>> handleAccessDeniedException(AccessDeniedException e) {
        return ResponseEntity.ok(new ApiResponse<>(ApiResponseCode.FORBIDDEN, e.getMessage(), null));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<String>> handleException(Exception e) {
        // 未知异常处理
        ExceptionUtil.logError("全局异常处理", e);
        ExceptionUtil.consoleError("全局异常处理:", e);
        return ResponseEntity.ok(new ApiResponse<>(ApiResponseCode.ERROR, e.getMessage(), null));
    }
}
